package com.linko.soundrecorder;

import android.app.ActionBar;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.ListPreference;
import android.preference.Preference;
import android.preference.PreferenceFragment;
import android.preference.PreferenceManager;
import android.preference.PreferenceScreen;
import android.text.TextUtils;
import android.util.Log;
import android.view.MenuItem;

import com.linko.soundrecorder.StorageHelper.Storage;

import java.io.File;
import java.util.ArrayList;

/**
 * Created by zhongrz on 15-3-27.
 */
public class SettingsActivity extends Activity {
    public static String KEY_FILE_STORAGE_PATH = "pref_key_storage_path";
    public static String KEY_RECORD_TYPE = "pref_key_record_type";
    public static String KEY_ENABLE_HIGH_QUALITY = "pref_key_record_quality";
    public static String KEY_ENABLE_SOUND_EFFECT = "pref_key_record_effect";
    public static String key_enable_keep_record_when_calling = "pref_key_keep_record_when_calling";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.fragment_settings);
        SettingsFragment settingsFragment = new SettingsFragment();
        getFragmentManager().beginTransaction().replace(R.id.settings_container, settingsFragment, "record_fragment").commit();

        initActionBar();
    }

    public void initActionBar() {
        ActionBar actionBar = getActionBar();
        actionBar.setDisplayHomeAsUpEnabled(true);
        actionBar.setDisplayShowHomeEnabled(false);
        actionBar.setBackgroundDrawable(getResources().getDrawable(R.drawable.title_bar_bg_color));
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        if (item.getItemId() == android.R.id.home) {
            onBackPressed();
        }
        return true;
    }

    public static class SettingsFragment extends PreferenceFragment implements
            Preference.OnPreferenceChangeListener, Preference.OnPreferenceClickListener {
        private final String TAG = SettingsFragment.class.getSimpleName();
        private final String KEY_RECORD_TYPE_PREF = "pref_key_record_type";
        private final String KEY_RECORD_STORAGE_PATH = "pref_key_storage_path";
        private PreferenceScreen mPreferenceScreen;
        private ListPreference mRecordTypePref;
        private Preference mRecordStoragePathPref;

        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            addPreferencesFromResource(R.xml.settings_layout);
            mPreferenceScreen = getPreferenceScreen();
            mRecordTypePref = (ListPreference) mPreferenceScreen.findPreference(KEY_RECORD_TYPE_PREF);
            mRecordTypePref.setOnPreferenceChangeListener(this);
            mRecordStoragePathPref = mPreferenceScreen.findPreference(KEY_RECORD_STORAGE_PATH);
            mRecordStoragePathPref.setOnPreferenceClickListener(this);
            updatePreference();
        }

        @Override
        public void onResume() {
            super.onResume();
            updatePreference();
        }

        @Override
        public boolean onPreferenceChange(Preference preference, Object value) {
            Log.i(TAG, "onPreferenceChange");
            if (preference instanceof ListPreference) {
                if (KEY_RECORD_TYPE_PREF.equals(preference.getKey())) {
                    String newValue = (String) value;
                    ListPreference prefrence = (ListPreference) preference;
                    prefrence.getEditor().putString(KEY_RECORD_TYPE_PREF, newValue).commit();
                    CharSequence type = newValue.subSequence(newValue.indexOf("/") + 1, newValue.length());
                    prefrence.setSummary(type);
                    return true;
                }

            }
            return false;
        }

        @Override
        public boolean onPreferenceClick(Preference preference) {
            if (preference == mRecordStoragePathPref) {
                StorageHelper storageHelper = StorageHelper.getInstance(getActivity());
                AlertDialog.Builder builder = new AlertDialog.Builder(getActivity(),
                        AlertDialog.THEME_HOLO_LIGHT);
                builder.setTitle(getActivity().getString(R.string.pref_dialog_title_storage_path));
                final ArrayList<Storage> storagesList = storageHelper.getStorageList();
                CharSequence[] storages = new CharSequence[storagesList.size()];
                for (int i = 0; i < storagesList.size(); i++) {
                    storages[i] = getActivity().getString(storagesList.get(i).descriptionId);
                }
                builder.setItems(storages, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        mRecordStoragePathPref.getEditor().putString(mRecordStoragePathPref.getKey(), storagesList.get(which).mountPoint)
                                .commit();
                        updatePreference();
                    }
                });
                builder.create().show();
            }
            return true;
        }

        private void updatePreference() {
            StorageHelper storageHelper = StorageHelper.getInstance(getActivity());
            ArrayList<Storage> storagesList = storageHelper.getMountedStorageList();
            if (storagesList.size() == 0) {
                mRecordStoragePathPref.setSummary(getString(R.string.storage_invalid));
                mRecordStoragePathPref.setEnabled(false);
            } else if (storagesList.size() == 1) {
                mRecordStoragePathPref.getEditor().putString(mRecordStoragePathPref.getKey(), storagesList.get(0).mountPoint)
                        .commit();
                mRecordStoragePathPref.setEnabled(false);
            } else {
                mRecordStoragePathPref.setEnabled(true);
            }
            String preferPath = mRecordStoragePathPref.getSharedPreferences().getString(mRecordStoragePathPref.getKey(),
                    storageHelper.getInternalSdcardPath());
            for (Storage storage : storagesList) {
                if (TextUtils.equals(storage.mountPoint, preferPath)) {
                    String path = getString(storage.descriptionId) + File.separator + Recorder.SAMPLE_DEFAULT_DIR;
                    mRecordStoragePathPref.setSummary(path);
                }
            }

            String typeValue = mRecordTypePref.getValue();
            CharSequence type = typeValue.subSequence(typeValue.indexOf("/") + 1, typeValue.length());
            mRecordTypePref.setSummary(type);
        }
    }

    /**
     * if the path user had set is unmounted,set one storage path whitch is mounted as default.
     */
    public static String getPrefStoragePath(Context context) {
        StorageHelper storageHelper = StorageHelper.getInstance(context);
        SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(context);
        String prefStoragePath = settings.getString(KEY_FILE_STORAGE_PATH,
                storageHelper.getInternalSdcardPath());
        if (!StorageHelper.isVolumeMounted(prefStoragePath)) {
            ArrayList<Storage> storagesList = storageHelper.getMountedStorageList();
            if (storagesList.size() > 0) {
                String stroagePath = storagesList.get(0).mountPoint;
                settings.edit().putString(KEY_FILE_STORAGE_PATH, stroagePath).commit();
                return stroagePath;
            }
        }

        return settings.getString(KEY_FILE_STORAGE_PATH, storageHelper.getInternalSdcardPath());
    }

    public static String getRecordType(Context context) {
        SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(context);
        return settings.getString(KEY_RECORD_TYPE, context.getString(R.string.pref_default_record_type));
    }

    public static boolean isHighQuality(Context context) {
        SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(context);
        return settings.getBoolean(KEY_ENABLE_HIGH_QUALITY, false);
    }

    public static boolean isEnabledSoundEffect(Context context) {
        SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(context);
        return settings.getBoolean(KEY_ENABLE_SOUND_EFFECT, false);
    }

    public static boolean isKeepRecordingWhenCalling(Context context) {
        SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(context);
        return settings.getBoolean(key_enable_keep_record_when_calling, false);
    }

}
